package com.meixiang.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.google.gson.Gson;
import com.meixiang.R;
import com.meixiang.activity.WebviewActivity;
import com.meixiang.activity.account.AccountMessageActivity;
import com.meixiang.activity.account.AccountSettingActivity;
import com.meixiang.activity.account.BindMemberCardActivity;
import com.meixiang.activity.account.CollectActivity;
import com.meixiang.activity.account.CouponActivity;
import com.meixiang.activity.account.MemberCardActivity;
import com.meixiang.activity.account.MyConcernActivity;
import com.meixiang.activity.account.login.LoginActivity;
import com.meixiang.activity.account.manager.AccountManageActivity;
import com.meixiang.activity.account.manager.VerifyRealNameActivity;
import com.meixiang.activity.account.managers.myPurse.MyPurseActivity;
import com.meixiang.activity.account.myAppointment.MyAllAppointmentActivity;
import com.meixiang.activity.account.myShopper.MyAllOrderActivity;
import com.meixiang.activity.account.myfund.MyFundActivity;
import com.meixiang.activity.homes.shopping.ShoppingCartActivity;
import com.meixiang.activity.moments.CommunityNewsActivity;
import com.meixiang.activity.moments.MyPostActivity;
import com.meixiang.entity.account.UserInfo;
import com.meixiang.global.Config;
import com.meixiang.global.ContentHint;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseFragment;
import com.meixiang.main.MXApplication;
import com.meixiang.main.MainActivity;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.util.GlideHelper;
import com.meixiang.view.swipetoloadlayout.base.OnLoadMoreListener;
import com.meixiang.view.swipetoloadlayout.base.OnRefreshListener;
import com.meixiang.view.swipetoloadlayout.base.SwipeToLoadLayout;
import com.lzy.okhttputils.model.HttpParams;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Response;
import yicheng.android.ui.materialdesignlibrary.views.LayoutRipple;


/**
 * 我的
 * <p>
 * 作者：黑哥 on 2016/3/29 11:39
 */
public class MyFragment extends BaseFragment implements OnRefreshListener, OnLoadMoreListener {
    /**
     * 登录按钮
     */
    @Bind(R.id.tv_login)
    TextView mTvLogin;
    /**
     * 消息
     */
    @Bind(R.id.tv_remind)
    ImageView mTvRemind;
    /**
     * 设置
     */
    @Bind(R.id.tv_setting)
    ImageView mTvSetting;
    /**
     * 头像
     */
    @Bind(R.id.iv_portrait)
    ImageView mIvPortrait;
    /**
     * 用户名
     */
    @Bind(R.id.tv_username)
    TextView mTvUsername;
    /**
     * 会员
     */
    @Bind(R.id.tv_gold_member)
    TextView mTvGoldMember;
    /**
     * 账户管理
     */
    @Bind(R.id.tv_account_manager)
    TextView mTvAccountManager;
    @Bind(R.id.my_member_card)
    LayoutRipple mMyMemberCard;
    @Bind(R.id.my_coupon)
    LayoutRipple mMyCoupon;
    @Bind(R.id.my_shopping_cart)
    LayoutRipple mMyShoppingCart;
    @Bind(R.id.my_collect)
    LayoutRipple mMyCollect;
    /**
     * 购物车
     */
    @Bind(R.id.tv_my_shopping)
    TextView mTvMyShopping;
    @Bind(R.id.rl_my_shopping)
    RelativeLayout mRlMyShopping;
    @Bind(R.id.my_payment)
    LayoutRipple mMyPayment;
    @Bind(R.id.my_take_delivery)
    LayoutRipple mMyTakeDelivery;
    @Bind(R.id.my_comment)
    LayoutRipple mMyComment;
    @Bind(R.id.my_refund)
    LayoutRipple mMyRefund;
    @Bind(R.id.tv_my_appointment)
    TextView mTvMyAppointment;
    @Bind(R.id.rl_my_appointment)
    RelativeLayout mRlMyAppointment;
    @Bind(R.id.my_appointment_payment)
    LayoutRipple mMyAppointmentUse;
    @Bind(R.id.my_appointment_use)
    LayoutRipple mMyAppointmentTakeDelivery;
    @Bind(R.id.my_appointment_comment)
    LayoutRipple mMyAppointmentComment;
    @Bind(R.id.my_appointment_refund)
    LayoutRipple mMyAppointmentRefund;
    /**
     * 我的钱包
     */
    @Bind(R.id.tv_my_wallet)
    TextView mTvMyWallet;
    @Bind(R.id.tv_my_by_stages)
    TextView mTvMyByStages;
    @Bind(R.id.my_community)
    TextView mMyCommunity;
    @Bind(R.id.rl_my_community)
    RelativeLayout mRlMyCommunity;
    /**
     * 发布
     */
    @Bind(R.id.tv_my_release)
    TextView mTvMyRelease;
    @Bind(R.id.my_release)
    LayoutRipple mMyRelease;
    /**
     * 关注
     */
    @Bind(R.id.tv_my_attention)
    TextView mTvMyAttention;
    @Bind(R.id.my_attention)
    LayoutRipple mMyAttention;
    /**
     * 消息列表
     */
    @Bind(R.id.tv_my_message_list)
    TextView mTvMyMessageList;
    @Bind(R.id.my_message_list)
    LayoutRipple mMyMessageList;

    /**
     * 优惠券
     */
    @Bind(R.id.tv_my_coupon)
    TextView mTvMyCoupon;
    /**
     * 收藏
     */
    @Bind(R.id.tv_my_collect)
    TextView mTvMyCollect;
    /**
     * 账户余额
     */
    @Bind(R.id.tv_my_account_balance)
    TextView mTvMyAccountBalance;
    /**
     * 累计收益
     */
    @Bind(R.id.tv_my_accumulated_income)
    TextView mTvMyAccumulatedIncome;
    /**
     * 可用余额
     */
    @Bind(R.id.tv_my_available_redit)
    TextView mTvMyAvailableRedit;
    /**
     * 我的保险
     */
    @Bind(R.id.rl_my_manage_insurance)
    RelativeLayout mRlMyManageInsurance;
    @Bind(R.id.refresh)
    SwipeToLoadLayout mRefresh;
    @Bind(R.id.swipe_target)
    ScrollView mSwipeTarget;


    private MainActivity activity;
    private View view;
    private String AvailablePredeposit;
    private String storeId;//storeId会员id
    private String haveCard;//是否有会员卡

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        view = inflater.inflate(R.layout.fragment_my, container, false);
        activity = (MainActivity) getActivity();
        super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, view);
        return view;
    }

    @Override
    protected void initTitle() {

    }

    @Override
    protected void initView() {
        //先执行这个方法
        mRefresh.setOnRefreshListener(this);
        mRefresh.setOnLoadMoreListener(this);
        mRefresh.setLoadMoreEnabled(false);


        if (MXApplication.mApp.hasLogin()) {
            mTvLogin.setVisibility(View.GONE);
            mIvPortrait.setVisibility(View.VISIBLE);
            mTvUsername.setVisibility(View.VISIBLE);
            mTvGoldMember.setVisibility(View.VISIBLE);
            mTvAccountManager.setVisibility(View.VISIBLE);

            //自动刷新
//            mRefresh.post(new Runnable() {
//                @Override
//                public void run() {
//                    mRefresh.setRefreshing(true);
//                }
//            });

            getUserinfo();
        }


    }

    @Override
    protected void setData() {

    }


    private void getUserinfo() {

        HttpParams params = new HttpParams();
        HttpUtils.post(Config.USERINFO_URL, params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {

//                mRefresh.setRefreshing(false);
                //接口数据类型问题  暂不转换
                MXApplication.mApp.clearUser();
                UserInfo mUserInfo = new Gson().fromJson(result.toString(), UserInfo.class);
                GlideHelper.showCircleImage(getActivity(), result.optString("memberAvatar"), R.mipmap.default_head_portrait, mIvPortrait);
                if(AbStrUtil.isEmpty(result.optString("memberNickname"))&& AbStrUtil.isEmpty(result.optString("memberName"))){
                    mTvUsername.setText("暂无昵称");
                }
                if (AbStrUtil.isEmpty(result.optString("memberNickname"))) {
                    mTvUsername.setText(result.optString("memberName"));
                } else {
                    mTvUsername.setText(result.optString("memberNickname"));
                }
                if (AbStrUtil.isEmpty(result.optString("memberGradeName"))) {
                    mTvGoldMember.setText("普通会员");
                } else {
                    mTvGoldMember.setText(result.optString("memberGradeName") + "会员");
                }

                storeId = result.optString("storeId");
                HashMap<String, String> vals = new HashMap<String, String>();
                vals.put("memberId", result.optString("memberId"));
                MXApplication.mApp.getSession().set(vals);

                MXApplication.mApp.setUser(mUserInfo);
                mTvMyAccountBalance.setText("账户余额：" + result.optString("availablePredeposit") + "元");

                /*mTvMyAccumulatedIncome.setText("累计收益：" + 0.00 + "元");
                mTvMyAvailableRedit.setText("可用额度：" + 0.00 + "元");*/
                AvailablePredeposit = result.optString("availablePredeposit");
                getmyCommunity();
            }

            @Override
            public void onError(String code, String message) {
//                mRefresh.setRefreshing(false);
                AbToastUtil.showToast(activity, message);
            }


            @Override
            public void onAfter(boolean isFromCache, JSONObject jsonObject, Call call, Response response, Exception e) {
                super.onAfter(isFromCache, jsonObject, call, response, e);
                mRefresh.setRefreshing(false);
            }
        });
    }

    //消息
    private void getmyCommunity() {

        HttpParams params = new HttpParams();
        HttpUtils.post(Config.SERVER_URL + "me/myCommunity", params, new HttpCallBack(getActivity()) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Log.e("TAG","输出当前 我的钱包数据 ="+result.toString());
                if (!TextUtils.isEmpty(result.optString("myCouponSize")))
                    mTvMyCoupon.setText("优惠券" + "(" + result.optString("myCouponSize") + ")");
                else
                    mTvMyCoupon.setText("优惠券");
                if (!TextUtils.isEmpty(result.optString("myGoodsCartSize")))
                    mTvMyShopping.setText("购物车" + "(" + result.optString("myGoodsCartSize") + ")");
                else
                    mTvMyShopping.setText("购物车");
                if (!TextUtils.isEmpty(result.optString("myFavoritesSize")))
                    mTvMyCollect.setText("收藏" + "(" + result.optString("myFavoritesSize") + ")");
                else
                    mTvMyCollect.setText("收藏");

                if (!TextUtils.isEmpty(result.optString("myPublishSize")))
                    mTvMyRelease.setText(result.optString("myPublishSize"));
                else
                    mTvMyRelease.setText("0");
                if (!TextUtils.isEmpty(result.optString("myConcernSize")))
                    mTvMyAttention.setText(result.optString("myConcernSize"));
                else
                    mTvMyAttention.setText("0");
                if (!TextUtils.isEmpty(result.optString("messageList")))
                    mTvMyMessageList.setText(result.optString("messageList"));
                else
                    mTvMyMessageList.setText("0");

                haveCard = result.optString("haveCard");
            }

            @Override
            public void onError(String code, String message) {
                AbToastUtil.showToast(activity, message);
            }

        });
    }


    @Override
    public void onLoadMore() {
        mRefresh.setLoadingMore(false);
    }

    @Override
    public void onRefresh() {
        getUserinfo();
    }


    @Override
    public void onResume() {
        super.onResume();
//        getUserinfo();
        if (!MXApplication.mApp.hasLogin()) {
            mTvLogin.setVisibility(View.VISIBLE);
            mIvPortrait.setVisibility(View.GONE);
            mTvUsername.setVisibility(View.GONE);
            mTvGoldMember.setVisibility(View.GONE);
            mTvAccountManager.setVisibility(View.GONE);
            mTvMyCoupon.setText("优惠券");
            mTvMyShopping.setText("购物车");
            mTvMyCollect.setText("收藏");
            mTvMyRelease.setText("0");
            mTvMyAttention.setText("0");
            mTvMyMessageList.setText("0");
        } else {
            mTvLogin.setVisibility(View.GONE);
            mIvPortrait.setVisibility(View.VISIBLE);
            mTvUsername.setVisibility(View.VISIBLE);
            mTvGoldMember.setVisibility(View.VISIBLE);
            mTvAccountManager.setVisibility(View.VISIBLE);
            getUserinfo();
        }

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_login, R.id.tv_remind, R.id.tv_setting, R.id.tv_account_manager, R.id.my_member_card, R.id.my_coupon, R.id.my_shopping_cart, R.id.my_collect, R.id.rl_my_shopping, R.id.my_payment, R.id.my_take_delivery, R.id.my_comment, R.id.my_refund, R.id.rl_my_appointment, R.id.my_appointment_payment, R.id.my_appointment_use, R.id.my_appointment_comment, R.id.my_appointment_refund, R.id.rl_my_wallet, R.id.tv_my_manage_money, R.id.rl_my_manage_money, R.id.rl_my_by_stages
            , R.id.rl_my_manage_insurance, R.id.my_release, R.id.my_attention, R.id.my_message_list})
    public void onClick(View view) {
        if (!MXApplication.mApp.hasLogin()) {
            startActivity(LoginActivity.class);
            return;
        }

        Intent intent = new Intent();
        switch (view.getId()) {
            case R.id.tv_login://登录
                startActivity(new Intent(activity, LoginActivity.class));
                break;
            case R.id.tv_remind://消息
                startActivity(new Intent(activity, AccountMessageActivity.class));
                break;
            case R.id.tv_setting://设置
                startActivity(new Intent(activity, AccountSettingActivity.class));
                break;
            case R.id.tv_account_manager://账户管理
                startActivity(new Intent(activity, AccountManageActivity.class));
                break;
            case R.id.my_member_card://会员卡
                /**如果没网给个提示 ruturn出去*/
                if (!Tool.isNetworkAvailable(activity)) {
                    Tool.showTextToast(activity, "连接出错，请检查网络后重试");
                    return;
                }
                if (haveCard.equals("N")) {
                    startActivity(new Intent(activity, BindMemberCardActivity.class));
                } else {
                    startActivity(new Intent(activity, MemberCardActivity.class));
                }
                break;
            case R.id.my_coupon://优惠券
                intent.setClass(getActivity(), CouponActivity.class);
                intent.putExtra("fromCode", "1");
                startActivity(intent);
                break;
            case R.id.my_shopping_cart://购物车
                startActivity(new Intent(activity, ShoppingCartActivity.class));
                break;
            case R.id.my_collect://收藏
                startActivity(CollectActivity.class);
                break;
            case R.id.rl_my_shopping://我的购物--查看全部购物
                startActivity(new Intent(activity, MyAllOrderActivity.class));
                break;
            case R.id.my_payment://待付款
                if (!MXApplication.mApp.hasLogin()) {
                    startActivity(new Intent(activity, LoginActivity.class));
                } else {
                    intent.setClass(getActivity(), MyAllOrderActivity.class);
                    intent.putExtra("status", "待付款");
                    startActivity(intent);
                }
                break;
            case R.id.my_take_delivery://待收货
                intent.setClass(getActivity(), MyAllOrderActivity.class);
                intent.putExtra("status", "待收货");
                startActivity(intent);
                break;
            case R.id.my_comment://待评价
                intent.setClass(getActivity(), MyAllOrderActivity.class);
                intent.putExtra("status", "待评价");
                startActivity(intent);
                break;
            case R.id.my_refund://退款/售后
                intent.setClass(getActivity(), MyAllOrderActivity.class);
                intent.putExtra("status", "退款/售后");
                startActivity(intent);
                break;
            case R.id.rl_my_appointment://我的预约
                startActivity(new Intent(activity, MyAllAppointmentActivity.class));
                break;
            case R.id.my_appointment_payment://我的预约--待付款
                intent.setClass(getActivity(), MyAllAppointmentActivity.class);
                intent.putExtra("status", "待付款");
                startActivity(intent);
                break;
            case R.id.my_appointment_use://我的预约--待使用
                intent.setClass(getActivity(), MyAllAppointmentActivity.class);
                intent.putExtra("status", "待使用");
                startActivity(intent);
                break;
            case R.id.my_appointment_comment://我的预约--待评价
                intent.setClass(getActivity(), MyAllAppointmentActivity.class);
                intent.putExtra("status", "待评价");
                startActivity(intent);
                break;
            case R.id.my_appointment_refund://我的预约--退款/售后
                intent.setClass(getActivity(), MyAllAppointmentActivity.class);
                intent.putExtra("status", "退款/售后");
                startActivity(intent);
                break;
            case R.id.rl_my_wallet://我的钱包
                intent.setClass(getActivity(), MyPurseActivity.class);
                intent.putExtra("AvailablePredeposit", AvailablePredeposit);
                startActivity(intent);
                break;
            case R.id.rl_my_manage_money://我的ji基金
//                startActivity(new Intent(activity, MyMoneyManagementActivity.class));
                startActivity(new Intent(activity, MyFundActivity.class));

                break;
            case R.id.rl_my_manage_insurance://我的保险
                if (!Tool.isNetworkAvailable(activity)) {
                    Tool.showTextToast(activity, "连接出错，请检查网络后重试");
                    return;
                }
                if (MXApplication.mApp.getUser().getRealNameAuthentication().equals("0")) {
                    intent.setClass(getActivity(), VerifyRealNameActivity.class);
                    startActivity(intent);
                } else {
                    intent.setClass(getActivity(), WebviewActivity.class);
                    intent.putExtra("url", Config.MY_INSURANCE);
                    intent.putExtra("title", "我的保险");
                    startActivity(intent);
                }
                break;
            case R.id.rl_my_by_stages://我的分期
//                    startActivity(new Intent(activity, StagingActivity.class));
                Tool.showTextToast(activity, ContentHint.COMING_SONN);
                //测试支付
                break;
            case R.id.my_release://发布
                startActivity(new Intent(activity, MyPostActivity.class));
                break;
            case R.id.my_attention://关注
                startActivity(new Intent(activity, MyConcernActivity.class));
                break;
            case R.id.my_message_list://消息列表
                startActivity(new Intent(activity, CommunityNewsActivity.class));
                break;
        }
    }
}
